package org.bdware.doip.core.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import org.apache.log4j.Logger;
import org.bdware.doip.core.doipMessage.*;

import java.util.List;

@ChannelHandler.Sharable
public class DelimiterMessageServerCodec extends MessageToMessageCodec<ByteBuf, DoipMessage> {
    private static Logger logger = Logger.getLogger(DelimiterMessageServerCodec.class);
    DelimiterMessageCodec codec = new DelimiterMessageCodecImpl();

    @Override
    protected void encode(ChannelHandlerContext ctx, DoipMessage msg, List<Object> out) throws Exception{
        logger.debug("server encode message");
        byte[] respBytes = codec.ResponseToBytes(msg);
        ByteBuf buff = Unpooled.directBuffer();
        logger.debug("server sending message: "+ new String(respBytes));
        buff.writeBytes(respBytes);
        out.add(buff);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out){
        logger.info("server decode message");
        byte[] reqestBytes = new byte[msg.readableBytes()];
        msg.readBytes(reqestBytes);
        DoipMessage reqest = codec.BytesToRequest(reqestBytes);

        out.add(reqest);
    }
}
